from flask import current_app, render_template, flash
from threading import Thread

from app import mail
from flask_mail import Message


def send_async_email(app, msg):
    with app.app_context():
        try:
            mail.send(msg)
        except Exception as e:
            flash('邮件发送失败！')
            print(e)


def send_mail(to, title, template, **kwargs):
    # python email
    # msg = Message('测试邮件', sender='459699024@qq.com', body='Test',
    #               recipients=['459699024@qq.com'])
    msg = Message('[鱼书]' + ' ' + title,
                  sender=current_app.config['MAIL_USERNAME'],
                  recipients=[to])
    msg.html = render_template(template, **kwargs)
    # mail.send(msg)
    app = current_app._get_current_object()
    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()